package com.sqx.modules.task.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserCertificationService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.bidding.dao.HelpBiddingDao;
import com.sqx.modules.bidding.entity.HelpBidding;
import com.sqx.modules.bidding.service.HelpBiddingService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.fixedClassify.entity.FixedClassify;
import com.sqx.modules.fixedClassify.service.FixedClassifyService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.repairRecord.entity.RepairRecord;
import com.sqx.modules.repairRecord.service.RepairRecordService;
import com.sqx.modules.taking.entity.Game;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.GameService;
import com.sqx.modules.task.dao.HelpOrderDao;
import com.sqx.modules.task.dao.HelpTakeDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpTakeService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 接单订单
 *
 * @author fang
 * @date 2021/1/8
 */
@Slf4j
@Service
public class HelpTakeServiceImpl extends ServiceImpl<HelpTakeDao, HelpTake> implements HelpTakeService {

    @Autowired
    private HelpTakeDao helpTakeDao;
    @Autowired
    private HelpOrderDao helpOrderDao;
    @Autowired
    private WxService wxService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private FixedClassifyService classifyService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private GameService gameService;
    @Autowired
    private HelpBiddingService biddingService;

    @Resource
    private HelpBiddingDao helpBiddingDao;

    @Autowired
    private UserCertificationService userCertificationService;
    @Autowired
    private RepairRecordService repairRecordService;
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);


    @Override
    public Result selectHelpTake(int page, int limit) {
        return Result.success().put("data", helpTakeDao.selectList(new QueryWrapper<>()));
    }

    @Override
    public Result selectRunHelpOrder(int page, int limit, Integer status, Integer taskType, String orderNo, String phone,
                                     String startTime, String deliveryTime, Long userId,String content,String gameId,String name) {
        Page<Map<String, Object>> pages = new Page<>(page, limit);
        IPage<Map<String, Object>> mapIPage = helpTakeDao.selectRunHelpOrder(pages, status, taskType, orderNo,
                phone, startTime, deliveryTime, userId,content,gameId,name);
        return Result.success().put("data", new PageUtils(mapIPage));
    }

    @Override
    public Result selectRunHelpOrder(int page, int limit, Integer status, String phone, String startTime, String endTime, Integer taskType, Long rideUserId, String userName) {
        phone = phone.trim();
        Page<Map<String, Object>> pages = new Page<>(page, limit);
        IPage<Map<String, Object>> mapIPage = helpTakeDao.selectRunHelpOrderList(pages, status, phone, startTime, endTime, taskType, rideUserId, userName);
        return Result.success().put("data", new PageUtils(mapIPage));
    }

    @Override
    public ExcelData helpTakeListExcel(Integer status, String phone, String startTime, String endTime, Integer taskType, Long rideUserId, String rideName) {
        phone = phone.trim();
        List<Map<String, Object>> mapIPage = helpTakeDao.helpTakeListExcel(status, phone, startTime, endTime, taskType, rideUserId, rideName);
        int index = 0;
        ExcelData data = new ExcelData();
        data.setName("接单列表");
        List<String> titles = new ArrayList();
        titles.add("编号");
        titles.add("发单用户");
        titles.add("接单用户");
        titles.add("服务类型");
        titles.add("服务分类");
        titles.add("下单人姓名");
        titles.add("下单人手机号");
        titles.add("下单人地址");
        titles.add("提交内容");
        titles.add("接单价格");
        titles.add("一级佣金");
        titles.add("二级佣金");
        titles.add("平台佣金");
        titles.add("服务开始时间");
        titles.add("服务结束时间");
        titles.add("服务开始地址");
        titles.add("服务结束地址");
        titles.add("服务开始经度");
        titles.add("服务开始纬度");
        titles.add("服务结束经度");
        titles.add("服务结束纬度");
//        titles.add("服务开始前图片");
//        titles.add("服务结束后图片");
        titles.add("确认码");
        titles.add("订单备注");
        titles.add("预约时间");
        titles.add("状态");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (Map<String, Object> map : mapIPage) {
            List<Object> row = new ArrayList();
            row.add(map.get("helpTakeId"));
            row.add(map.get("userName"));
            row.add(map.get("helpTakeUserName"));
            if ("1".equals(String.valueOf(map.get("taskType")))) {
                row.add("悬赏任务");
            } else if ("2".equals(String.valueOf(map.get("taskType")))) {
                row.add("报价任务");
            } else {
                row.add("一口价任务");
            }
            row.add(map.get("serviceName"));
            row.add(map.get("name"));
            row.add(map.get("phone"));
            row.add(String.valueOf(map.get("province")) + String.valueOf(map.get("city")) + String.valueOf(map.get("district")) + String.valueOf(map.get("detailsAddress")));
            row.add(map.get("content"));
            row.add(map.get("money"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("zhiMoney"))) ? 0 : map.get("zhiMoney"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("feiMoney"))) ? 0 : map.get("feiMoney"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("pingMoney"))) ? 0 : map.get("pingMoney"));

            row.add(StringUtils.isBlank(String.valueOf(map.get("startTime"))) ? " " : map.get("startTime"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("startTime"))) ? " " : map.get("endTime"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("startTaskAddress"))) ? " " : map.get("startTaskAddress"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("endTaskAddress"))) ? " " : map.get("endTaskAddress"));

            row.add(StringUtils.isBlank(String.valueOf(map.get("startTaskLatitude"))) ? " " : map.get("startTaskLatitude"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("startTaskLongitude"))) ? " " : map.get("startTaskLongitude"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("endTaskLatitude"))) ? " " : map.get("endTaskLatitude"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("endTaskLongitude"))) ? " " : map.get("endTaskLongitude"));
//            row.add(StringUtils.isBlank(String.valueOf(map.get("startTaskImg")))?" ":map.get("startTaskImg"));
//            row.add(StringUtils.isBlank(String.valueOf(map.get("endTaskImg")))?" ":map.get("endTaskImg"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("code"))) ? " " : map.get("code"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("remarks"))) ? " " : map.get("remarks"));
            row.add(StringUtils.isBlank(String.valueOf(map.get("deliveryTime"))) ? " " : map.get("deliveryTime"));
            String status1 = String.valueOf(map.get("status"));
            //1 已接单  2 已送达  3已下架
            if ("1".equals(status1)) {
                row.add("待服务");
            } else if ("2".equals(status1)) {
                row.add("进行中");
            } else if ("3".equals(status1)) {
                row.add("已完成");
            } else if ("4".equals(status1)) {
                row.add("已取消");
            } else {
                row.add("未知");
            }
            rows.add(row);
        }
        index++;
        log.error("==============" + index);
        data.setRows(rows);
        return data;


    }

    @Override
    public Result adminDistributionOrder(Long orderId, Long userId) {
        CommonInfo commonInfo = commonInfoService.findOne(616);
        UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("user_id", userId));

        if (userEntity.getIsAuthentication() == null) {
            return Result.error("当前商家或师傅未认证");
        }
        UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("user_id", userEntity.getUserId()));
        if (userMoney.getSafetyMoney().compareTo(new BigDecimal(commonInfo.getValue())) < 0) {
            return Result.error(508,"当前用户未缴纳足额" + commonInfo.getValue() + "元的保证金");
        }
        reentrantReadWriteLock.writeLock().lock();
        try {
            HelpOrder helpOrder = helpOrderDao.selectById(orderId);
            if (helpOrder.getStatus() != 1) {
                return Result.error("订单已被抢走了");
            }
            HelpTake helpTake = new HelpTake();
            helpTake.setOrderId(helpOrder.getId());
            helpTake.setStatus(1);
            helpTake.setCreateTime(new Date());
            helpTake.setUserId(userId);
            helpTake.setTaskType(helpOrder.getTaskType());
            helpTake.setMoney(helpOrder.getCommission());
            helpTakeDao.insertHelpTake(helpTake);
            helpOrder.setHelpTakeId(helpTake.getId());
            int code = (int) ((Math.random() * 9 + 1) * 1000);
            helpOrder.setCode(String.valueOf(code));
            helpOrder.setStatus(2);
            helpOrderDao.updateById(helpOrder);
            UserEntity user = userService.selectUserById(helpOrder.getUserId());
            if (user.getClientid() != null) {
                userService.pushToSingle("任务通知", "您的任务已被接单！", user.getClientid());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("您的任务已被接单！");
            messageInfo.setTitle("任务通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(user.getUserName());
            messageInfo.setUserId(String.valueOf(user.getUserId()));
            messageService.saveBody(messageInfo);
            String value = commonInfoService.findOne(312).getValue();
            FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
            UserEntity userEntity1 = userService.getById(helpOrder.getUserId());
            if (StringUtils.isNotBlank(userEntity1.getOpenId())) {
                List<String> msgList = new ArrayList<>();
                msgList.add(helpOrder.getOrderNo());
                msgList.add(fixedClassify.getClassifyName());
                msgList.add("师傅已接单");
                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                msgList.add("您的任务已被接单");
                SenInfoCheckUtil.sendMsg(userEntity1.getOpenId(), value, 1, msgList, 4);
            }
            UserEntity riderUser = userService.getById(userId);
            if (StringUtils.isNotBlank(riderUser.getShopOpenId())) {
                List<String> msgList = new ArrayList<>();
                msgList.add(helpOrder.getOrderNo());
                msgList.add(fixedClassify.getClassifyName());
                msgList.add("已接单");
                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                msgList.add("您有一条管理员派单的订单");
                SenInfoCheckUtil.sendMsg(riderUser.getShopOpenId(), value, 1, msgList, 4);
            }

            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请刷新后重试！");


    }

    @Override
    public HelpTake selectHelpTakeById(Long helpTakeId) {
        HelpTake helpTake = helpTakeDao.selectById(helpTakeId);
        if (helpTake != null) {
            UserEntity userEntity = userService.selectUserById(helpTake.getUserId());
            helpTake.setUser(userEntity);
        }
        return helpTake;
    }


    @Override
    public Integer countHelpTakeByCreateTime(String time, Integer flag) {
        return helpTakeDao.countHelpTakeByCreateTime(time, flag);
    }

    @Override
    public Double sumMoneyBySend(String time, Integer flag) {
        return helpTakeDao.sumMoneyBySend(time, flag);
    }


    /**
     * 接单
     *
     * @param helpTake 接单实体类
     * @return 是否接单成功
     */
    @Override
    public Result saveBody(HelpTake helpTake) {
        CommonInfo commonInfo = commonInfoService.findOne(616);
        UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("user_id", helpTake.getUserId()));
        if (userEntity.getIsAuthentication() == null) {
            return Result.error("当前用户未认证");
        }

        UserMoney userMoney = userMoneyService.getOne(new QueryWrapper<UserMoney>().eq("user_id", userEntity.getUserId()));
        if (userMoney.getSafetyMoney().compareTo(new BigDecimal(commonInfo.getValue())) < 0) {
            return Result.error(508,"当前用户未缴纳足额" + commonInfo.getValue() + "元的保证金");
        }

        reentrantReadWriteLock.writeLock().lock();
        try {
            HelpOrder helpOrder = helpOrderDao.selectById(helpTake.getOrderId());
            if (helpOrder.getStatus() != 1) {
                return Result.error("系统繁忙，请刷新后重试！");
            }
            helpTake.setStatus(1);
            helpTake.setCreateTime(new Date());
            helpTake.setTaskType(helpOrder.getTaskType());
            helpTake.setMoney(helpOrder.getCommission());
            helpTakeDao.insertHelpTake(helpTake);
            helpOrder.setHelpTakeId(helpTake.getId());
            int code = (int) ((Math.random() * 9 + 1) * 1000);
            helpOrder.setCode(String.valueOf(code));
            helpOrder.setStatus(2);
            helpOrderDao.updateById(helpOrder);
            UserEntity user = userService.selectUserById(helpOrder.getUserId());
            if (user.getClientid() != null) {
                userService.pushToSingle("任务通知", "您的任务已被接单！", user.getClientid());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("您的任务已被接单！");
            messageInfo.setTitle("任务通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(user.getUserName());
            messageInfo.setUserId(String.valueOf(user.getUserId()));
            messageService.saveBody(messageInfo);
            String value = commonInfoService.findOne(312).getValue();
            FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
            UserEntity userEntity1 = userService.getById(helpOrder.getUserId());

            if (StringUtils.isNotBlank(userEntity1.getOpenId())) {
                List<String> msgList = new ArrayList<>();
                msgList.add(helpOrder.getOrderNo());
                msgList.add(fixedClassify.getClassifyName());
                msgList.add("师傅已接单");
                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                msgList.add("您的任务已被接单");
                SenInfoCheckUtil.sendMsg(userEntity1.getOpenId(), value, 1, msgList, 4);
            }
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请刷新后重试！");
    }


    @Override
    public Result endHelpTake(Long id, Long userId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            HelpTake helpTake = helpTakeDao.selectById(id);
            if (!helpTake.getStatus().equals(1)) {
                return Result.error("系统繁忙，请稍后再试！");
            }
            helpTakeDao.deleteById(helpTake.getId());
            HelpOrder helpOrder = helpOrderDao.selectById(helpTake.getOrderId());
            if (helpOrder.getTaskType() == 2) {
                if (!helpRefund(helpOrder)) {
                    return Result.error("取消订单失败");
                } else {
                    helpOrder.setCommission(BigDecimal.ZERO);
                    helpOrder.setMoney(BigDecimal.ZERO);

                    // 刪除报价人与这个订单的关系
//                    helpBiddingDao.delete(new LambdaQueryWrapper<HelpBidding>().eq(HelpBidding::getHelperId, helpOrder.getId()).eq(HelpBidding::getUserId, userId));

                    // 修改报价人与订单的关系
                    HelpBidding helpBidding = new HelpBidding();
                    helpBidding.setStatus(2);
                    helpBiddingDao.update(helpBidding,new LambdaQueryWrapper<HelpBidding>().eq(HelpBidding::getHelperId, helpOrder.getId()).eq(HelpBidding::getUserId, userId));
                }
            }else if(helpOrder.getTaskType() == 4){
                if (helpOrder.getPayWay() == null || helpOrder.getPayWay() == 1) {
                    userMoneyService.updateMoney(1, helpOrder.getUserId(), helpOrder.getMoney());
                } else if (helpOrder.getPayWay() == 2) {
                    //微信
                    boolean refund = wxService.refund(helpOrder.getOrderNo(), helpOrder.getMoney());
                    if (!refund) {
                        return Result.error("退款失败，请联系客服处理！");
                    }
                } else {
                    //支付宝
                    String data = aliPayController.alipayRefund(helpOrder.getOrderNo(), helpOrder.getMoney());
                    if (StringUtils.isNotBlank(data)) {
                        log.error(data);
                        JSONObject jsonObject = JSON.parseObject(data);
                        JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                        String code1 = alipay_trade_refund_response.getString("code");
                        if (!"10000".equals(code1)) {
                            return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                        }
                    } else {
                        return Result.error("退款失败！");
                    }
                }
                FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setUserId(helpOrder.getUserId());
                userMoneyDetails.setTitle("[万能任务退款]：" + fixedClassify.getClassifyName());
                userMoneyDetails.setContent("万能任务已原路退款：" + helpOrder.getMoney());
                userMoneyDetails.setType(1);
                userMoneyDetails.setMoney(helpOrder.getMoney());
                userMoneyDetails.setCreateTime(DateUtils.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
                helpOrder.setHelpTakeId(-1L);
                helpOrder.setStatus(5);
                helpOrderDao.updateById(helpOrder);
                UserEntity user = userService.selectUserById(helpOrder.getUserId());
                if (user.getClientid() != null) {
                    userService.pushToSingle("订单通知", "您的订单取消成功！", user.getClientid());
                }
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("您的订单取消成功！");
                messageInfo.setTitle("订单通知");
                messageInfo.setState(String.valueOf(4));
                messageInfo.setUserName(user.getUserName());
                messageInfo.setUserId(String.valueOf(user.getUserId()));
                messageService.saveBody(messageInfo);

                String value = commonInfoService.findOne(312).getValue();

                if (StringUtils.isNotBlank(user.getOpenId())) {
                    List<String> msgList = new ArrayList<>();
                    msgList.add(helpOrder.getOrderNo());
                    msgList.add(fixedClassify.getClassifyName());
                    msgList.add("订单已取消");
                    msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                    msgList.add("您的订单取消成功");
                    SenInfoCheckUtil.sendMsg(user.getOpenId(), value, 1, msgList, 4);
                }
                return Result.success();
            }
            helpOrder.setHelpTakeId(-1L);
            helpOrder.setStatus(1);
            helpOrderDao.updateById(helpOrder);
            UserEntity user = userService.selectUserById(helpOrder.getUserId());
            if (user.getClientid() != null) {
                userService.pushToSingle("订单通知", "您的订单已被取消，系统已经帮你重新发布！", user.getClientid());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("您的订单已被取消，系统已经帮你重新发布！");
            messageInfo.setTitle("订单通知");
            messageInfo.setState(String.valueOf(4));
            messageInfo.setUserName(user.getUserName());
            messageInfo.setUserId(String.valueOf(user.getUserId()));
            messageService.saveBody(messageInfo);

            String value = commonInfoService.findOne(312).getValue();
            FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
            if (StringUtils.isNotBlank(user.getOpenId())) {
                List<String> msgList = new ArrayList<>();
                msgList.add(helpOrder.getOrderNo());
                msgList.add(fixedClassify.getClassifyName());
                msgList.add("订单已取消");
                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                msgList.add("订单已被取消,系统已经帮你重新发布");
                SenInfoCheckUtil.sendMsg(user.getOpenId(), value, 1, msgList, 4);
            }

            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("取消订单报错："+e.getMessage(),e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请刷新后重试！");
    }

    /**
     * 师傅主动取消竞价订单后退款给用户。
     *
     * @param helpOrder
     * @return
     */
    public boolean helpRefund(HelpOrder helpOrder) {

        boolean result;
        if (helpOrder.getPayWay() == 1) {
            userMoneyService.updateMoney(1, helpOrder.getUserId(), helpOrder.getMoney());
            result = true;
        } else if (helpOrder.getPayWay() == 2) {
            //微信
            boolean refund = wxService.refund(helpOrder.getOrderNo(), helpOrder.getMoney());
            if (!refund) {
                result = false;
            } else {
                result = true;
            }
        } else {
            String data = aliPayController.alipayRefund(helpOrder.getOrderNo(), helpOrder.getMoney());
            if (data != null) {
                JSONObject jsonObject = JSON.parseObject(data);
                JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                String code1 = alipay_trade_refund_response.getString("code");
                if (!"10000".equals(code1)) {
                    result = false;
                } else {
                    result = true;
                }
            } else {
                result = false;
            }
        }
        if (result) {
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(helpOrder.getUserId());
            userMoneyDetails.setTitle("万能任务订单取消退款");
            userMoneyDetails.setContent("万能任务订单取消,支付金额已原路退还");
            userMoneyDetails.setType(1);
            userMoneyDetails.setMoney(helpOrder.getMoney());
            userMoneyDetails.setState(1);
            userMoneyDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        return result;
    }

    /**
     * 确认送达
     *
     * @param helpTakeId  接单id
     * @param helpOrderId 派单id
     * @param code        收货码
     * @return 是否送达成功
     */
    @Override
    public Result closeOrder(Long helpTakeId, Long helpOrderId, String code, String endTaskImg, String endTaskAddress, String endTaskLongitude, String endTaskLatitude, int type) {
        HelpOrder helpOrder = helpOrderDao.selectById(helpOrderId);
        HelpTake helpTake = helpTakeDao.selectById(helpOrder.getHelpTakeId());
        if (helpOrder.getStatus() != 3) {
            return Result.error("请刷新后重试！");
        }

        if (type != 2 && !helpOrder.getCode().equals(code)) {
            return Result.error("确认码不正确！");
        }
        if (helpTake.getStatus() != 2) {
            return Result.error("当前服务暂未开始");
        }
        if (type != 2 && endTaskImg.split(",").length < 4) {
            return Result.error("完成服务请上传最少4张图片");
        }
        if(type != 2 && (StringUtils.isEmpty(endTaskLongitude) || StringUtils.isEmpty(endTaskLatitude)) ){
            return Result.error("请打开定位权限！");
        }
        String endAddress=null;
        if(type!=2){
            String way = commonInfoService.findOne(414).getValue();
            if("1".equals(way)){
                CommonInfo one = commonInfoService.findOne(217);
                String url = "https://apis.map.qq.com/ws/geocoder/v1/";
                Map<String, String> maps = new HashMap<>();
                maps.put("location", endTaskLatitude + "," + endTaskLongitude);
                maps.put("key", one.getValue());
                String data = HttpClientUtil.doGet(url, maps);
                JSONObject jsonObject = JSON.parseObject(data);
                String statuss = jsonObject.getString("status");
                if ("0".equals(statuss)) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    endAddress = result.getString("address");
                } else {
                    log.error("转换失败！！！原因:" + jsonObject.getString("message"));
                }

            }else{
                String value = commonInfoService.findOne(415).getValue();
                String url="http://api.tianditu.gov.cn/geocoder";
                Map<String,String> param=new HashMap<>();
                JSONObject postStr=new JSONObject();
                postStr.put("lon",endTaskLongitude);
                postStr.put("lat",endTaskLatitude);
                postStr.put("ver","1");
                param.put("postStr",postStr.toJSONString());
                param.put("type","geocode");
                param.put("tk",value);
                String s = HttpClientUtil.doGet(url,param);
                JSONObject jsonObject = JSONObject.parseObject(s);
                String statuss = jsonObject.getString("status");
                if("0".equals(statuss)){
                    JSONObject result = jsonObject.getJSONObject("result");
                    endAddress = result.getString("formatted_address");
                }else {
                    log.error("转换失败！！！原因:" + jsonObject.getString("msg"));
                }
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());

        helpOrder.setStatus(4);


        helpTake.setStatus(3);
        helpTake.setEndTaskImg(endTaskImg);
        helpTake.setEndTime(new Date());

        helpTake.setEndTaskLongitude(endTaskLongitude);
        helpTake.setEndTaskLatitude(endTaskLatitude);
        helpTake.setEndTaskAddress(endAddress);


        UserEntity entity = userService.getById(helpTake.getUserId());

        BigDecimal refundMoney=BigDecimal.ZERO;
        if(helpOrder.getRefundMoney()!=null){
            refundMoney=helpOrder.getRefundMoney();
        }
        BigDecimal ordersMoney = helpOrder.getMoney().subtract(refundMoney);
        BigDecimal sumMoney = ordersMoney;
        List<RepairRecord> list = repairRecordService.list(new QueryWrapper<RepairRecord>().eq("order_no", helpOrder.getOrderNo()).eq("order_type", 1));
        for (RepairRecord record:list){
            refundMoney=BigDecimal.ZERO;
            if(record.getRefundMoney()!=null){
                refundMoney=record.getRefundMoney();
            }
            BigDecimal recordMoney = record.getPayMoney().subtract(refundMoney);
            sumMoney=sumMoney.add(recordMoney);
        }


        BigDecimal riderMoney = entity.getRate().multiply(sumMoney);
        helpTake.setMoney(riderMoney);
        helpOrder.setCommission(riderMoney);
        helpOrderDao.updateById(helpOrder);


        userMoneyService.updateMoney(1, helpTake.getUserId(), helpTake.getMoney());
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setUserId(helpTake.getUserId());
        FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
        userMoneyDetails.setTitle("[接单完成]：" + fixedClassify.getClassifyName());
        DecimalFormat df=new DecimalFormat("0.00");
        userMoneyDetails.setContent("增加金额:" + df.format(helpTake.getMoney()));
        userMoneyDetails.setType(1);
        userMoneyDetails.setMoney(helpTake.getMoney());
        userMoneyDetails.setCreateTime(date);
        userMoneyDetailsService.save(userMoneyDetails);

        BigDecimal pingMoney = sumMoney.subtract(helpTake.getMoney());
        BigDecimal zhiMoney = BigDecimal.ZERO;
        BigDecimal feiMoney = BigDecimal.ZERO;
        //判断是否开启分销
        String value = commonInfoService.findOne(209).getValue();
        if ("是".equals(value)) {
            //分销
            if (pingMoney.doubleValue() > 0) {
                UserEntity userEntity = userService.selectUserById(helpOrder.getUserId());
                //直属
                UserEntity zhiUser = userService.queryByInvitationCode(userEntity.getInviterCode());
                if (zhiUser != null) {
                    if (zhiUser.getZhiRate().doubleValue() != 0 && zhiUser.getZhiRate().doubleValue() > 0) {
                        zhiMoney = pingMoney.multiply(zhiUser.getZhiRate());
                        helpTake.setZhiMoney(zhiMoney);
                        helpTake.setZhiUserId(zhiUser.getUserId());
                        userMoneyService.updateMoney(1, zhiUser.getUserId(), zhiMoney);
                        userMoneyDetails = new UserMoneyDetails();
                        userMoneyDetails.setUserId(zhiUser.getUserId());
                        userMoneyDetails.setTitle("一级佣金订单完成：" + helpOrder.getOrderNo());
                        userMoneyDetails.setContent("一级佣金订单完成，到账金额：" + zhiMoney);
                        userMoneyDetails.setType(1);
                        userMoneyDetails.setMoney(zhiMoney);
                        userMoneyDetails.setCreateTime(date);
                        userMoneyDetailsService.save(userMoneyDetails);

                        //非直属
                        UserEntity feiUser = userService.queryByInvitationCode(zhiUser.getInviterCode());
                        if (feiUser != null) {
                            if (feiUser.getFeiRate().doubleValue() != 0 && feiUser.getFeiRate().doubleValue() > 0) {
                                feiMoney = pingMoney.multiply(feiUser.getFeiRate());
                                helpTake.setFeiMoney(feiMoney);
                                helpTake.setFeiUserId(feiUser.getUserId());
                                userMoneyService.updateMoney(1, feiUser.getUserId(), feiMoney);
                                userMoneyDetails = new UserMoneyDetails();
                                userMoneyDetails.setUserId(feiUser.getUserId());
                                userMoneyDetails.setTitle("二级佣金订单完成：" + helpOrder.getOrderNo());
                                userMoneyDetails.setContent("二级佣金订单完成，到账金额：" + feiMoney);
                                userMoneyDetails.setType(1);
                                userMoneyDetails.setMoney(feiMoney);
                                userMoneyDetails.setCreateTime(date);
                                userMoneyDetailsService.save(userMoneyDetails);
                            }
                        }
                    }
                }
            }

        }

        if (zhiMoney.doubleValue() > 0) {
            pingMoney = pingMoney.subtract(zhiMoney);
        }
        if (feiMoney.doubleValue() > 0) {
            pingMoney = pingMoney.subtract(feiMoney);
        }
        helpTake.setPingMoney(pingMoney);
        helpTakeDao.updateById(helpTake);
        UserCertification userCertification = userCertificationService.getOne(new QueryWrapper<UserCertification>().eq("user_id", helpTake.getUserId()));
        if(userCertification!=null){
            if(userCertification.getServiceNum()==null){
                userCertification.setServiceNum(0);
            }
            userCertification.setServiceNum(userCertification.getServiceNum()+1);
            userCertificationService.updateById(userCertification);
        }

        UserEntity userEntity = userService.selectUserById(helpOrder.getUserId());
        if (userEntity.getClientid() != null) {
            userService.pushToSingle("订单通知", "您的订单已经完成！", userEntity.getClientid());
        }
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent("您的订单已经完成！");
        messageInfo.setTitle("订单通知");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageService.saveBody(messageInfo);
        String one = commonInfoService.findOne(312).getValue();
        if (StringUtils.isNotBlank(userEntity.getOpenId())) {
            List<String> msgList = new ArrayList<>();
            msgList.add(helpOrder.getOrderNo());
            msgList.add(fixedClassify.getClassifyName());
            msgList.add("订单已完成");
            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            msgList.add("师傅已完成订单,有疑问请联系客服");
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one, 1, msgList, 4);
        }
        return Result.success();
    }

    @Override
    public Result closeOrders(Long helpOrderId) {
        HelpOrder helpOrder = helpOrderDao.selectById(helpOrderId);
        if (helpOrder.getStatus() != 3) {
            return Result.error("请刷新后重试！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        HelpTake helpTake = helpTakeDao.selectById(helpOrder.getHelpTakeId());
        helpOrder.setStatus(4);
        helpTake.setStatus(3);
        helpTake.setEndTime(new Date());
        helpOrderDao.updateById(helpOrder);
        helpTakeDao.updateById(helpTake);
        userMoneyService.updateMoney(1, helpTake.getUserId(), helpTake.getMoney());
        Game game = gameService.getById(helpOrder.getGameId());
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setUserId(helpTake.getUserId());
        DecimalFormat df=new DecimalFormat("0.00");
        userMoneyDetails.setTitle("[接单完成]：" + helpOrder.getOrderNo());
        userMoneyDetails.setContent("增加金额:" + df.format(helpTake.getMoney()));
        userMoneyDetails.setType(1);
        userMoneyDetails.setMoney(helpTake.getMoney());
        userMoneyDetails.setCreateTime(date);
        userMoneyDetailsService.save(userMoneyDetails);
        UserEntity userEntity = userService.selectUserById(helpOrder.getUserId());
        if (userEntity.getClientid() != null) {
            userService.pushToSingle("订单通知", "您的订单已经完成！", userEntity.getClientid());
        }
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent("您的订单已经完成！");
        messageInfo.setTitle("订单通知");
        messageInfo.setState(String.valueOf(4));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageService.saveBody(messageInfo);
        String value = commonInfoService.findOne(312).getValue();
        FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
        if (StringUtils.isNotBlank(userEntity.getOpenId())) {
            List<String> msgList = new ArrayList<>();
            msgList.add(helpOrder.getOrderNo());
            msgList.add(fixedClassify.getClassifyName());
            msgList.add("订单已完成");
            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            msgList.add("点击查看订单详情");
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), value, 1, msgList, 4);
        }
        return Result.success();
    }


    @Override
    public Result updateHelpTakeById(HelpTake helpTake) {
        helpTakeDao.updateById(helpTake);
        return Result.success();
    }

    @Override
    public Result deleteById(Long id) {
        helpTakeDao.deleteById(id);
        return Result.success();
    }

    @Override
    public Result offerOrder(Long id, BigDecimal offerMoney, Integer userType,Long userId) {
        HelpOrder helpOrder = helpOrderDao.selectById(id);
        FixedClassify classify = classifyService.getById(helpOrder.getFixedClassifyId());
        if (classify != null) {
            if (offerMoney.compareTo(classify.getMinQuoteMoney()) < 0) {
                return Result.error("报价金额不得低于" + classify.getMinQuoteMoney() + "元");
            }
        }
        if (helpOrder.getTaskType() == 2) {
            HelpBidding bidding = biddingService.getOne(new QueryWrapper<HelpBidding>().eq("helper_id", helpOrder.getId()).eq("user_id", userId));
            if (bidding == null) {
                int count = biddingService.count(new QueryWrapper<HelpBidding>().eq("helper_id", helpOrder.getId()).ne("status",2));
                if (count >= helpOrder.getMaxPeople()) {
                    return Result.error("报价人数已满!");
                }
                HelpBidding helpBidding = new HelpBidding();
                helpBidding.setHelperId(helpOrder.getId());
                helpBidding.setUserId(userId);
                helpBidding.setStatus(0);
                helpBidding.setOfferMoney(offerMoney);
                helpBidding.setUserType(userType);
                biddingService.save(helpBidding);
            } else {
                return Result.error("您已经报价过了");
            }
            UserEntity user = userService.selectUserById(helpOrder.getUserId());
            if (user.getClientid() != null) {
                userService.pushToSingle("任务通知", "已有人对您的任务进行报价！", user.getClientid());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("你的任务已被报价！");
            messageInfo.setTitle("任务通知");
            messageInfo.setState(String.valueOf(4));
            messageInfo.setUserName(user.getUserName());
            messageInfo.setUserId(String.valueOf(user.getUserId()));
            String value = commonInfoService.findOne(312).getValue();
            FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
            if (StringUtils.isNotBlank(user.getOpenId())) {
                List<String> msgList = new ArrayList<>();
                msgList.add(helpOrder.getOrderNo());
                msgList.add(fixedClassify.getClassifyName());
                msgList.add("订单被报价");
                msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
                msgList.add("你的任务已被报价,点击查看详情");
                SenInfoCheckUtil.sendMsg(user.getOpenId(), value, 1, msgList, 4);
            }


            return Result.upStatus(messageService.saveBody(messageInfo));
        } else {
            return Result.error("当前订单不能报价");
        }

    }

    @Override
    public Result startHelperOrder(Long helpOrderId, Long userId, String startTaskImg, String startTaskAddress, String startTaskLongitude, String startTaskLatitude) {
        HelpOrder helpOrder = helpOrderDao.selectById(helpOrderId);
        if (helpOrder == null) {
            return Result.error("任务不存在!");
        }
        HelpTake helpTake = helpTakeDao.selectById(helpOrder.getHelpTakeId());
        if (helpTake == null) {
            return Result.error("订单不存在!");
        }
        if (!userId.equals(helpTake.getUserId()) && !userId.equals(helpTake.getCompanyId())) {
            return Result.error("你无权操作此订单");
        }
        String[] split = startTaskImg.split(",");
        if (split.length < 4) {
            return Result.error("开始服务请上传最少4张图片");
        }
        if(StringUtils.isEmpty(startTaskLongitude) || StringUtils.isEmpty(startTaskLatitude) ){
            return Result.error("请打开定位权限！");
        }
        String startAddress=null;
        String way = commonInfoService.findOne(414).getValue();
        if("1".equals(way)){
            CommonInfo one = commonInfoService.findOne(217);
            String url = "https://apis.map.qq.com/ws/geocoder/v1/";
            Map<String, String> maps = new HashMap<>();
            maps.put("location", startTaskLatitude + "," + startTaskLongitude);
            maps.put("key", one.getValue());
            String data = HttpClientUtil.doGet(url, maps);
            JSONObject jsonObject = JSON.parseObject(data);
            String statuss = jsonObject.getString("status");
            if ("0".equals(statuss)) {
                JSONObject result = jsonObject.getJSONObject("result");
                startAddress = result.getString("address");
            } else {
                log.error("转换失败！！！原因:" + jsonObject.getString("message"));
            }
        }else{
            String value = commonInfoService.findOne(415).getValue();
            String url="http://api.tianditu.gov.cn/geocoder";
            Map<String,String> param=new HashMap<>();
            JSONObject postStr=new JSONObject();
            postStr.put("lon",startTaskLongitude);
            postStr.put("lat",startTaskLatitude);
            postStr.put("ver","1");
            param.put("postStr",postStr.toJSONString());
            param.put("type","geocode");
            param.put("tk",value);
            String s = HttpClientUtil.doGet(url,param);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String statuss = jsonObject.getString("status");
            if("0".equals(statuss)){
                JSONObject result = jsonObject.getJSONObject("result");
                startAddress = result.getString("formatted_address");
            }else {
                log.error("转换失败！！！原因:" + jsonObject.getString("msg"));
            }
        }
        if(StringUtils.isEmpty(startAddress)){
            return Result.error("获取定位失败！");
        }
        helpOrder.setStatus(3);
        helpOrderDao.updateById(helpOrder);
        helpTake.setStatus(2);
        helpTake.setStartTime(new Date());
        helpTake.setStartTaskLongitude(startTaskLongitude);
        helpTake.setStartTaskLatitude(startTaskLatitude);
        helpTake.setStartTaskImg(startTaskImg);


        helpTake.setStartTaskAddress(startAddress);
        String value = commonInfoService.findOne(312).getValue();
        FixedClassify fixedClassify = classifyService.getById(helpOrder.getFixedClassifyId());
        UserEntity userEntity = userService.getById(helpOrder.getUserId());

        if (StringUtils.isNotBlank(userEntity.getOpenId())) {
            List<String> msgList = new ArrayList<>();
            msgList.add(helpOrder.getOrderNo());
            msgList.add(fixedClassify.getClassifyName());
            msgList.add("开始服务");
            msgList.add(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            msgList.add("师傅已开始服务");
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), value, 1, msgList, 4);
        }


        return Result.upStatus(helpTakeDao.updateById(helpTake));
    }

    @Override
    public IPage<List<HashMap<String, Object>>> orderStatistics(Integer page, Integer limit, Long companyId, String phone, String userName, String startTime, String endTime) {
        IPage<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return helpTakeDao.orderStatistics(pages, companyId, phone, userName, startTime, endTime);

    }

    @Override
    public IPage<HashMap<String, Object>> getMyOfferOrder(Integer page, Integer limit, Integer status, Long userId) {
        IPage<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return helpTakeDao.getMyOfferOrder(pages, status, userId);
    }

    @Override
    public HashMap<String, Object> getCompanyOrderCount(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        //当天
        Integer todayCount = helpTakeDao.selectCount(new QueryWrapper<HelpTake>().eq("company_id", userId).eq("status", 3).apply("date_format(end_time,'%Y-%m-%d') = {0}", DateFormatUtils.format(new Date(), "yyyy-MM-dd")));
        //总共
        Integer allCount = helpTakeDao.selectCount(new QueryWrapper<HelpTake>().eq("company_id", userId).eq("status", 3));
        map.put("todayCount", todayCount);
        map.put("allCount", allCount);
        return map;
    }

    @Override
    public IPage<HashMap<String, Object>> getCompanyOrder(Integer page, Integer limit, Integer status, Long userId, Long companyId, Long userIds) {
        IPage<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        UserEntity userEntity = userService.getById(userIds);
        if (userEntity.getCompanyId() != null) {
            userIds = userEntity.getCompanyId();
        }
        return helpOrderDao.getCompanyOrder(pages, status, userId, companyId, userIds);
    }

    @Override
    public Result distributionOrder(Long companyId, Long takeId) {
        HelpTake take = helpTakeDao.selectOne(new QueryWrapper<HelpTake>().eq("id", takeId));
        take.setCompanyId(companyId);
        int i = helpTakeDao.updateById(take);
        HelpOrder helpOrder = helpOrderDao.selectById(take.getOrderId());
        UserEntity userEntity = userService.selectUserById(companyId);
        String templateId = commonInfoService.findOne(621).getValue();
        if(StringUtils.isNotBlank(userEntity.getOpenId())){
            List<String> msgList=new ArrayList<>();
            msgList.add(helpOrder.getOrderNo());
            String serviceName = helpOrder.getContent();
            if(serviceName.length()>15){
                serviceName=serviceName.substring(0,15)+"...";
            }
            msgList.add(serviceName);
            msgList.add(helpOrder.getDeliveryTime());
            msgList.add(helpOrder.getName());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,null,msgList,6);
        }
        if(StringUtils.isNotBlank(userEntity.getPhone())){
            userService.sendMsg(userEntity.getPhone(),"assignTask",null);
        }
        return Result.upStatus(i);
    }

    @Override
    public IPage<HashMap<String, Object>> getStaffOrder(Integer page, Integer limit, Long userId) {
        IPage<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getStaffOrder(pages, userId);
    }

    @Override
    public IPage<HashMap<String, Object>> getStaffUserHelp(Integer page, Integer limit, Long companyId) {
        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getStaffUserHelp(pages, companyId);


    }


    @Override
    public Integer selectHelpTakeCountByUserId(Long userId,Integer status,String startTime,String endTime){
        return baseMapper.selectHelpTakeCountByUserId(userId, status, startTime, endTime);
    }

    @Override
    public Double selectHelpTakeMoneyCountByUserId(Long userId,Integer type){
        return baseMapper.selectHelpTakeMoneyCountByUserId(userId, type);
    }



}
